package com.jin.crud.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jin.crud.bean.*;
import com.jin.crud.common.exception.ResultException;
import com.jin.crud.common.utils.SecurityUtils;
import com.jin.crud.dao.SysRoleMapper;
import com.jin.crud.dao.SysUserMapper;
import com.jin.crud.dao.SysUserRoleMapper;
import com.jin.crud.service.SysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author yuxuejin
 * @since 2021-11-16
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Value("${user.defaultPassword}")
    private String defaultPassword;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    SysUserRoleMapper userRoleMapper;

    @Override
    public PageInfo<SysUser> getAllPage(QueryDto param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<SysUser> page = userMapper.getByPage(param);
        return new PageInfo<>(page);
    }

    @Override
    public SysUser getUser(String userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public void addUser(SysUser user) {
        if (this.checkUserAccountUnique(user)) {
            throw new ResultException(2021001, "用户名已存在");
        } else if (this.checkPhoneUnique(user)) {
            throw new ResultException(2021002, "电话已存在");
        } else if (this.checkEmailUnique(user)) {
            throw new ResultException(2021003, "邮箱已存在");
        }
        String time = String.valueOf(System.currentTimeMillis());
        user.setCreateTime(time);
        user.setUpdateTime(time);
        user.setCreateBy("刘一手");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 新增用户信息
        userMapper.insertUser(user);
        // 新增用户岗位关联
        //insertUserPost(user);
        // 新增用户与角色管理
        if (com.jin.crud.common.utils.StringUtils.isNotEmpty(user.getRoleIds())) {
            insertUserRole(user);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user
     */
    private void insertUserRole(SysUser user) {
        String[] roles = user.getRoleIds();
        if (com.jin.crud.common.utils.StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (String roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }


    @Override
    public void updateUser(SysUser user) {
        if (StringUtils.isEmpty(String.valueOf(user.getUserId()))) {
            throw new ResultException(2021001, "修改失败，未检测到用户");
        } else if (this.checkPhoneUnique(user)) {
            throw new ResultException(2021002, "电话已存在");
        } else if (this.checkEmailUnique(user)) {
            throw new ResultException(2021003, "邮箱已存在");
        }
        String time = String.valueOf(System.currentTimeMillis());
        user.setCreateTime(time);
        user.setUpdateTime(time);
        user.setUpdateBy("刘一手");
        String userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        //userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        //insertUserPost(user);
        userMapper.updateUser(user);
    }

    @Override
    public void delUser(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new ResultException(2021003, "未找到用户ID");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setDelFlag("1");
        userMapper.updateUser(sysUser);
    }

    @Override
    public void updateUserStatus(String userId, String status) {
        if (StringUtils.isEmpty(userId)) {
            throw new ResultException(2021003, "未找到用户ID");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setStatus(status);
        sysUser.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        userMapper.updateUser(sysUser);
    }

    @Override
    public void checkUserAllowed(String userId) {
        if (StringUtils.isNotBlank(userId) && "1".equals(userId)) {
            throw new ResultException(20211001, "不允许操作超级管理员用户");
        }
    }

    @Override
    public void resetPwd(String userId) {
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(SecurityUtils.encryptPassword(defaultPassword));
        user.setUpdateBy("刘一手");
        userMapper.updateUser(user);
    }

    @Override
    public Map<String, Object> getAuthRole(String userId) {
        SysUser user = userMapper.selectUserById(userId);
        List<SysRole> roles = this.selectRolesByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return map;
    }

    @Override
    public void insertUserAuth(String userId, String[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        if (ObjectUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (String roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }

    }

    @Override
    public PageInfo<SysUser> selectAllocatedList(QueryUser param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<SysUser> page = userMapper.selectAllocatedList(param);
        return new PageInfo<>(page);
    }

    @Override
    public PageInfo<SysUser> selectUnallocatedList(QueryUser param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<SysUser> page = userMapper.selectUnallocatedList(param);
        return new PageInfo<>(page);
    }

    @Override
    public SysUser selectUserByUserAccount(String userAccount) {
        return userMapper.selectUserByUserAccount(userAccount);
    }

    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public SysUser selectUserById(String userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    public List<SysRole> selectRolesByUserId(String userId) {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = roleMapper.getByPage(new QueryDto());
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().equals(userRole.getRoleId())) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 验证账号唯一
     */
    public boolean checkUserAccountUnique(SysUser user) {
        String userId = StringUtils.isBlank(user.getUserId()) ? "ID is empty" : user.getUserId();
        String account = StringUtils.isBlank(user.getUserAccount()) ? "account is empty" : user.getUserAccount();
        SysUser sysUser = userMapper.checkUserAccountUnique(account);
        return ObjectUtils.isNotEmpty(sysUser) && !userId.equals(sysUser.getUserId());
    }

    /**
     * 验证手机号唯一
     */
    public boolean checkPhoneUnique(SysUser user) {
        String userId = StringUtils.isBlank(user.getUserId()) ? "ID is empty" : user.getUserId();
        String phonenumber = StringUtils.isBlank(user.getPhonenumber()) ? "phone is empty" : user.getPhonenumber();
        SysUser sysUser = userMapper.checkPhoneUnique(phonenumber);
        return ObjectUtils.isNotEmpty(sysUser) && !userId.equals(sysUser.getUserId());
    }

    /**
     * 验证邮箱唯一
     */
    public boolean checkEmailUnique(SysUser user) {
        String userId = StringUtils.isBlank(user.getUserId()) ? "ID is empty" : user.getUserId();
        String email = StringUtils.isBlank(user.getEmail()) ? "email is empty" : user.getEmail();
        SysUser sysUser = userMapper.checkEmailUnique(email);
        return ObjectUtils.isNotEmpty(sysUser) && !userId.equals(sysUser.getUserId());
    }

}
